import express from 'express';
import xlsx from 'xlsx';
import cors from 'cors';
import CryptoJS from 'crypto-js';
import jwt from 'jsonwebtoken';
import { fileURLToPath } from 'url';
import path from 'path';
import axios from 'axios';
import mysql from 'mysql2';
import WebSocket from 'ws';

const app = express();
const PORT = 3000;
const SECRET_KEY = 'my_secret_key_123';
const JWT_SECRET = 'jwt_secret_key_456';
const PASSWORD_SECRET = 'password_secret_456';

// 创建 HTTP 服务器
const server = app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
});

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  console.log('新连接已建立');

  // 监听来自客户端的消息
  ws.on('message', async (message) => {
    console.log('收到客户端消息:', message);

    // 将消息解析为 JSON 格式
    let parsedMessage;
    try {
      parsedMessage = JSON.parse(message);
    } catch (error) {
      console.error('消息解析失败:', error);
      return;
    }

    // 调用 AI 接口获取回复
    const requestBody = {
      model: "4.0Ultra",
      messages: parsedMessage.messages,
      stream: false,
      max_tokens: 1024
    };

    try {
      const aiResponse = await axios.post(
        'https://spark-api-open.xf-yun.com/v1/chat/completions',
        requestBody,
        {
          headers: {
            'Authorization': 'Bearer joRSxASbPrOtUadecqgA:OVtblvXIkRXQZGDhUEyw',
            'Content-Type': 'application/json',
          }
        }
      );

      // 获取 AI 回复
      const aiMessage = aiResponse.data.choices[0].message;

      // 将 AI 回复发送回客户端
      ws.send(JSON.stringify({ success: true, message: aiMessage }));
    } catch (error) {
      console.error('AI 请求错误:', error.response?.data || error);
      ws.send(JSON.stringify({ success: false, message: '服务器错误' }));
    }
  });

  // 监听连接关闭
  ws.on('close', () => {
    console.log('连接已关闭');
  });
});

